# -*- coding: utf-8 -*-
#
# upload file library
#
import sys
import os
import time
from StringIO import StringIO
from PIL import Image
from dmblog.settings import *
import ImageFilter


def upload_avatar(data):
    u"""
    summary:
        Upload user avatar    
    params:
        data    object  request.FILES.get('uploadcontrolname')
    returns:
        state  directory {'success
':True|False ,'message':error info|new file path}
    author:
        rsj217 <rsj217@gmail.com>
    """
    state = {
        'success': False,
        'message': '',
    }

    if data.size > 0:
        # try:
        base_im = Image.open(data)

        size50 = (50, 50)
        size150 = (150, 150)

        size_array = (size50, size150)

        # generate file name and the file path
        file_name = time.strftime('%Y%H%M%S') + '.jpeg'
        file_root_path = '%savatar/' % (MEDIA_ROOT)
        file_sub_path = '%s' % (str(time.strftime("%Y/%m/%d/")))

        # make different sizes photos
        for size in size_array:
            file_middle_path = '%d/' % size[0]

            file_path = os.path.abspath(
                file_root_path + file_middle_path + file_sub_path)

            im = base_im
            im = make_thumb(im, size[0])

            # check path exist
            if not os.path.exists(file_path):
                os.makedirs(file_path)

            im.save('%s/%s' % (file_path, file_name), 'jpeg')

        state['success'] = True
        state['message'] = file_sub_path + file_name

    else:
        state['success'] = False
        state['message'] = u'还未选择要上传的文件。'

    return state


def make_thumb(im, size=150):
    u"""
    summary:
        缩略图生成程序
    params:
        sizes   参数传递要生成的尺寸，可以生成多种尺寸
    author:
        rsj217
    """

    width, height = im.size
    if width == height:
        region = im
    else:
        if width > height:
            delta = (width - height) / 2
            box = (delta, 0, delta + height, height)
        else:
            delta = (height - width) / 2
            box = (0, delta, width, delta + width)
        region = im.crop(box)

    thumb = region.resize((size, size), Image.ANTIALIAS)
    return thumb
